<template>
  <div class="app-container">
    <div class="filter-container">
      <el-card>
        <el-form ref="searchform" :inline="true" :model="searchform" class="demo-form-inline" size="small">
          <el-form-item label="广告名称：">
            <el-input v-model="searchform.Keywords" clearable placeholder="广告名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch()">查询</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card>
      <div class="list-btn-container">
        <el-button-group>
          <slot v-for="itemf in loadBtnFunc">
            <el-button v-if="itemf.FullName==='新增'" type="default" icon="el-icon-plus" size="small" @click="ShowEditOrViewDialog()">新增</el-button>
            <el-button v-if="itemf.FullName==='修改'" type="default" icon="el-icon-edit" size="small" @click="ShowEditOrViewDialog('edit')">修改</el-button>
            <el-button v-if="itemf.FullName=='禁用'" type="default" icon="el-icon-video-pause" size="small" @click="setEnable('0')">禁用</el-button>
            <el-button v-if="itemf.FullName=='启用'" type="default" icon="el-icon-video-play" size="small" @click="setEnable('1')">启用</el-button>
            <el-button v-if="itemf.FullName==='软删除'" type="default" icon="el-icon-delete" size="small" @click="deleteSoft('0')">软删除</el-button>
            <el-button v-if="itemf.FullName==='删除'" type="default" icon="el-icon-delete" size="small" @click="deletePhysics()">删除</el-button>
            <el-button v-if="itemf.FullName==='重置密码'" type="default" icon="el-icon-refresh-right" size="small" @click="handleResetPassword()">重置密码</el-button>
          </slot>
          <el-button type="default" icon="el-icon-refresh" size="small" @click="loadTableData()">刷新</el-button>
        </el-button-group>
      </div>
      <el-table
        ref="gridtable"
        v-loading="tableloading"
        :data="tableData"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        :default-sort="{prop: 'SortCode', order: 'descending'}"
        @select="handleSelectChange"
        @select-all="handleSelectAllChange"
        @sort-change="handleSortChange"
      >
        <el-table-column
          type="selection"
          width="30"
        />
        <el-table-column
          prop="Title"
          label="名称"
          sortable="custom"
          width="230"
          fixed
        />
        <el-table-column
          prop="ADTitle"
          label="广告位"
          sortable="custom"
          width="230"
          fixed
        />
        <el-table-column
          prop="SortCode"
          label="排序"
          sortable="custom"
          width="230"
          fixed
        />
        <el-table-column
          prop="StartTime"
          label="开始时间"
          sortable="custom"
          width="180"
          fixed
        />
        <el-table-column
          prop="EndTime"
          label="结束时间"
          sortable="custom"
          width="190"
          align="center"
        />
        <el-table-column
          label="可用"
          sortable="custom"
          width="90"
          prop="EnabledMark"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.EnabledMark === true ? 'success' : 'info'"
              disable-transitions
            >{{ scope.row.EnabledMark===true?'启用':'禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="CreatorTime"
          label="添加时间"
          width="180"
          sortable
        />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="pagination.currentPage"
          :page-sizes="[5,10,20,50,100, 200, 300, 400]"
          :page-size="pagination.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.pageTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <el-dialog ref="dialogEditForm" :title="editFormTitle+'广告'" :visible.sync="dialogEditFormVisible" width="660px">
      <el-form ref="editFrom" :inline="true" :model="editFrom" :rules="rules" class="demo-form-inline">
        <el-form-item label="广告位" :label-width="formLabelWidth" prop="AdId">
          <el-select v-model="editFrom.AdId" clearable placeholder="请选择广告位" style="width:500px;">
            <el-option
              v-for="item in selectAdverts"
              :key="item.Id"
              :label="item.Title"
              :value="item.EnCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" :label-width="formLabelWidth" prop="Title">
          <el-input v-model="editFrom.Title" style="width:500px;" placeholder="请输入名称" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="开始时间" :label-width="formLabelWidth" prop="StartTime">
          <el-date-picker
            v-model="editFrom.StartTime"
            style="width:200px;"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="结束时间" :label-width="formLabelWidth" prop="EndTime">
          <el-date-picker
            v-model="editFrom.EndTime"
            type="date"
            style="width:200px;"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="链接类型" :label-width="formLabelWidth" prop="LinkType">
          <el-select v-model="editFrom.LinkType" clearable placeholder="请选链接类型" style="width:500px;">
            <el-option
              v-for="item in selectLinkType"
              :key="item.Id"
              :label="item.ItemName"
              :value="item.ItemCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth" prop="SortCode">
          <el-input-number v-model="editFrom.SortCode" min="0" style="width:500px;" placeholder="请输入排序" autocomplete="off" clearable @input="onInput()" />
        </el-form-item>
        <el-form-item label="链接" :label-width="formLabelWidth" prop="LinkUrl">
          <el-input v-model="editFrom.LinkUrl" style="width:500px;" placeholder="请输入链接" autocomplete="off" clearable @input="onInput()" />
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth" prop="FilePath">
          <el-upload
            :action="httpFileUploadUrl"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :limit="1"
            :file-list="filelist"
            :on-success="uploadFileSuccess"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogHeadIconVisible">
            <img width="100%" :src="dialogHeadIconImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getPage, save, getDetail, del, setEnable, delSoft } from '@/api/cms/bannerservice'
import { GetAllEnable } from '@/api/cms/advertservice'
import * as fecha from 'element-ui/lib/utils/date'
import defaultSettings from '@/settings'
import { getListItemDetailsByCode } from '@/api/basebasic'

export default {
  data() {
    return {
      searchform: {
        Keywords: ''
      },
      httpFileUploadUrl: defaultSettings.fileUploadUrl,
      filelist: [],
      dialogHeadIconVisible: false,
      dialogHeadIconImageUrl: '',
      selectAdverts: [],
      selectRole: [],
      selectedOrganizeOptions: '',
      selectOrganize: [],
      selectLinkType: [],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime())
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近两天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 2)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近两个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 60)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      loadBtnFunc: [],
      tableData: [],
      tableloading: true,
      pagination: {
        currentPage: 1,
        pagesize: 10,
        pageTotal: 0
      },
      sortableData: {
        order: '',
        sort: ''
      },
      dialogEditFormVisible: false,
      editFormTitle: '',
      editFrom: {
        Title: '',
        AdId: '',
        LinkType: '',
        FilePath: '',
        StartTime: null,
        EndTime: null,
        DeleteMark: false,
        SortCode: 99
      },
      rules: {
        Title: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 16 个字符', trigger: 'blur' }
        ],
        //  LinkUrl: [
        //   { required: true, message: '请输入链接', trigger: 'blur' },
        //   { min: 2, max: 50, message: '长度在 2 到 16 个字符', trigger: 'blur' }
        // ],
        AdId: [
          { required: true, message: '请选择广告位', trigger: 'blur' }
        ],
        LinkType: [
          { required: true, message: '请选择链接类型', trigger: 'blur' }
        ],
        FilePath: [
          { required: true, message: '请添加图片', trigger: 'blur' }
        ]
      },
      formLabelWidth: '80px',
      currentId: '',
      currentSelected: []
    }
  },
  created() {
    this.pagination.currentPage = 1
    this.InitDictItem()
    this.loadTableData()
    this.loadBtnFunc = JSON.parse(localStorage.getItem('yueboncurrentfuns'))
  },
  methods: {
    InitDictItem() {
      GetAllEnable().then(res => {
        this.selectAdverts = res.ResData
      })
      getListItemDetailsByCode('BannerLinkType').then(res => {
        this.selectLinkType = res.ResData
      })
    },
    loadTableData: function() {
      this.tableloading = true
      var seachdata = {
        'CurrentPage': this.pagination.currentPage,
        'length': this.pagination.pagesize,
        'Keywords': this.searchform.Keywords,
        'Order': this.sortableData.order,
        'Sort': this.sortableData.sort
      }
      getPage(seachdata).then(res => {
        this.tableData = res.ResData.Items
        this.pagination.pageTotal = res.ResData.TotalItems
        this.tableloading = false
      })
    },
    handleSearch: function() {
      this.pagination.currentPage = 1
      this.loadTableData()
    },
    ShowEditOrViewDialog: function(view) {
      if (view !== undefined) {
        if (this.currentSelected.length > 1 || this.currentSelected.length === 0) {
          this.$alert('请选择一条数据进行编辑/修改', '提示')
        } else {
          this.currentId = this.currentSelected[0].Id
          this.editFormTitle = '编辑'
          this.dialogEditFormVisible = true
          this.bindEditInfo()
        }
      } else {
        this.editFormTitle = '新增'
        this.currentId = ''
        this.selectedOrganizeOptions = ''
        this.dialogEditFormVisible = true
        this.filelist = []

        this.$nextTick(function() {
          this.$refs['editFrom'].resetFields()
        })
      }
    },
    bindEditInfo: function() {
      getDetail(this.currentId).then(res => {
        this.editFrom.Title = res.ResData.Title
        this.editFrom.AdId = res.ResData.AdId
        this.editFrom.EndTime = res.ResData.EndTime
        this.editFrom.StartTime = res.ResData.StartTime
        this.editFrom.LinkUrl = res.ResData.LinkUrl
        this.editFrom.LinkType = res.ResData.LinkType.toString()
        this.editFrom.DeleteMark = res.ResData.DeleteMark
        this.editFrom.FilePath = res.ResData.FilePath
        this.editFrom.SortCode = res.ResData.SortCode
        this.filelist = [{ name: res.ResData.FilePath, url: res.ResData.FilePath }]
        this.InitDictItem()
      })
    },
    /**
     * 新增/修改保存
     */
    saveEditForm() {
      console.log(this.editFrom.RoleId)
      this.$refs['editFrom'].validate((valid) => {
        if (valid) {
          const data = {
            Title: this.editFrom.Title,
            AdId: this.editFrom.AdId,
            StartTime: this.editFrom.StartTime,
            EndTime: this.editFrom.EndTime,
            FilePath: this.editFrom.FilePath,
            LinkUrl: this.editFrom.LinkUrl,
            LinkType: this.editFrom.LinkType,
            DeleteMark: this.editFrom.DeleteMark,
            SortCode:this.editFrom.SortCode,
            'Id': this.currentId
          }

          var url = 'banner/Insert'
          if (this.currentId !== '') {
            url = 'banner/Update?id=' + this.currentId
          }
          save(data, url).then(res => {
            if (res.Success) {
              this.$message({
                message: '恭喜你，操作成功',
                type: 'success'
              })
              this.dialogEditFormVisible = false
              this.currentSelected = ''
              this.selectedOrganizeOptions = ''
              this.$refs['editFrom'].resetFields()
              this.loadTableData()
              this.InitDictItem()
            } else {
              this.$message({
                message: res.ErrMsg,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    setEnable: function(val) {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        var currentIds = ''
        this.currentSelected.forEach(element => {
          currentIds += element.Id + ','
        })
        const data = {
          ids: currentIds,
          bltag: val
        }
        setEnable(data).then(res => {
          if (res.Success) {
            this.$message({
              message: '恭喜你，操作成功',
              type: 'success'
            })
            this.currentSelected = ''
            this.loadTableData()
          } else {
            this.$message({
              message: res.ErrMsg,
              type: 'error'
            })
          }
        })
      }
    },

    deleteSoft: function(val) {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        var currentIds = ''
        this.currentSelected.forEach(element => {
          currentIds += element.Id + ','
        })
        const data = {
          ids: currentIds,
          bltag: val
        }
        delSoft(data).then(res => {
          if (res.Success) {
            this.$message({
              message: '恭喜你，操作成功',
              type: 'success'
            })
            this.currentSelected = ''
            this.loadTableData()
          } else {
            this.$message({
              message: res.ErrMsg,
              type: 'error'
            })
          }
        })
      }
    },
    deletePhysics: function() {
      if (this.currentSelected.length === 0) {
        this.$alert('请先选择要操作的数据', '提示')
        return false
      } else {
        var currentIds = ''
        this.currentSelected.forEach(element => {
          currentIds += element.Id + ','
        })
        const data = {
          ids: currentIds
        }
        del(data).then(res => {
          if (res.Success) {
            this.$message({
              message: '恭喜你，操作成功',
              type: 'success'
            })
            this.currentSelected = ''
            this.loadTableData()
          } else {
            this.$message({
              message: res.ErrMsg,
              type: 'error'
            })
          }
        })
      }
    },
    /**
     * 当表格的排序条件发生变化的时候会触发该事件
     */
    handleSortChange: function(column) {
      this.sortableData.sort = column.prop
      if (column.order === 'ascending') {
        this.sortableData.order = 'asc'
      } else {
        this.sortableData.order = 'desc'
      }
      this.loadTableData()
    },
    /**
     * 当用户手动勾选checkbox数据行事件
     */
    handleSelectChange: function(selection, row) {
      this.currentSelected = selection
    },
    /**
     * 当用户手动勾选全选checkbox事件
     */
    handleSelectAllChange: function(selection) {
      this.currentSelected = selection
    },
    /**
     * 选择每页显示数量
     */
    handleSizeChange(val) {
      this.pagination.pagesize = val
      this.pagination.currentPage = 1
      this.loadTableData()
    },
    /**
     * 选择当页面
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadTableData()
    },
    dateformatter(row, column, cellValue, index) {
      var date = row[column.property]
      return cellValue ? fecha.format(new Date(date), 'yyyy-MM-dd') : ''
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.editFrom.FilePath = file.url
    },
    uploadFileSuccess: function(response, file, fileList) {
      this.editFrom.FilePath = defaultSettings.fileUrl + response.ResData.FilePath
      console.log(this.editFrom.FilePath)
    },
    onInput() {
      this.$forceUpdate()
    }
  }
}
</script>
